﻿using System;
using System.Configuration;
using Microsoft.Xrm.Client;
using Microsoft.Xrm.Client.Services;

namespace CrmWorkflowDependencies.Crm
{
    public sealed class XrmService : OrganizationService
    {
        private static volatile OrganizationService instance;
        private static object syncRoot = new Object();

        private XrmService() : base(String.Empty) { }

        public static OrganizationService Instance
        {
            get
            {
                if (instance == null)
                {
                    lock (syncRoot)
                    {
                        if (instance == null)
                        {
                            instance = GetOrganizationProxy();
                        }
                    }
                }

                return instance;
            }
        }

        const string _defaultConnectionStringName = "CRM_SERVICE";

        public static OrganizationService GetOrganizationProxy(string connectionStringName = null)
        {
            string connName = string.IsNullOrEmpty(connectionStringName) ? _defaultConnectionStringName : connectionStringName;
            var conn = ConfigurationManager.ConnectionStrings[connName];

            if (conn == null) throw new ConfigurationErrorsException(string.Format("connection string '{0}' not found", connName));

            // Establish a connection to the organization web service using CrmConnection
            // by parsing a string in the DbConnectionStringBuilder format
            CrmConnection connection = CrmConnection.Parse(conn.ConnectionString);

            return new OrganizationService(connection);
        }
    }
}